package top.codedance.iotp.iot.sdk;

import org.java_websocket.enums.ReadyState;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class StompWsClient implements Client {
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private StompWsContext client;
    private boolean isDestory = false;
    public StompWsClient(final String uri, String topic, String id, final WsCallbacker callbacker) {
        executorService.submit(() -> {
            try {
                client = new StompWsContext(uri, topic, id, callbacker);
                client.connect();
                while (!client.getReadyState().equals(ReadyState.OPEN)) {
                    Thread.sleep(500);
                }
                while (client.isOpen() && !isDestory){
                    Thread.sleep(500);
                }
            } catch (Exception e) { }
        });
    }

    @Override
    public void send(String body){
        client.send(body);
    }
    @Override
    public void destory(){
        isDestory = true;
    }
    @Override
    public boolean isOver(){
        return isDestory;
    }
    @Override
    public void waiting(){
        Object lock = new Object();
        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("WsClient over.");
            }
        }
        destory();
    }

    @Override
    public void reconnect() {
        client.reconnect();
    }
}
